var videosModel = require("../models/videos");
var administratorsModel = require("../models/admin");
var jwt = require("jsonwebtoken");
var usersModel = require("../models/users");
var {
  find,
  findOneByid,
  createOne,
  count,
  remove,
  groupBy,
  update,
  updateOne,

} = require("../dao/base.js");
var videolabelModel = require("../models/videolabel");

//注册
module.exports.register = async function (req, res, next) {
  var data = {
    userid: req.body.userid,
    password: req.body.password,
  };
  var doc = await findOneByid(administratorsModel, { userid: data.userid });
  if (doc != null) {
    res.sendResult(null, 403, "用户已存在！");
  } else {
    var doc2 = await createOne(administratorsModel, data);
    res.sendResult(doc2, 201, "用户创建成功！");
  }
};

//登录
module.exports.useridLogin = async (req, res, next) => {
  var userInfo = {
    userid: req.body.userid,
    password: req.body.password,
  };
  var doc = await find(administratorsModel, userInfo);
  console.log(doc.permission);
  if (doc.length > 0) {
    let secretOrPrivateKey = "admin projects.";
    var token =
      "bearer " +
      jwt.sign(userInfo, secretOrPrivateKey, {
        expiresIn: 60 * 60 * 24 * 7, // 一周过期
      });
    return res.sendResult(
      { userid: userInfo.userid, token,permission:doc[0].permission },
      200,
      "登录成功！"
    );
  } else {
    return res.sendResult(null, 403, "登录失败！");
  }
};

//获取全部视频
module.exports.getVideoList = async (req, res) => {
  var data = {
    curPage: page,
    pageSize: 6,
  };
  var page = req.query.page || 1;
  const total = await count(videosModel, {});
  var result2 = await find(videosModel, {}, null, {
    skip: (page - 1) * data.pageSize,
    limit: data.pageSize,
    sort: { _id: -1 },
  });
  if (result2) {
    return res.sendResult(result2, 200, total);
  }
};

//获取全部视频
module.exports.getUserList = async (req, res) => {
  var data = {
    curPage: page,
    pageSize: 6,
  };
  var page = req.query.page || 1;
  const total = await count(usersModel, {});
  var result2 = await find(usersModel, {}, null, {
    skip: (page - 1) * data.pageSize,
    limit: data.pageSize,
    sort: { _id: -1 },
  });
  if (result2) {
    return res.sendResult(result2, 200, total);
  }
};

//删除视频
module.exports.removeVideo = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  let myvideos = req.body.videoid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  let needRole = '视频管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }

  if (doc) {
    var result3 = await remove(videosModel, { _id: myvideos });
    res.sendResult(result3, 200, `删除了视频:${myvideos}`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//删除视频
module.exports.removeUser = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  let userid = req.body.userid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  let needRole = '用户管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  if (doc) {
    var result3 = await remove(usersModel, { userid });
    res.sendResult(result3, 200, `删除了用户:${userid}`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//删除用户
module.exports.removeUser = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  let userid = req.body.userid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  let needRole = '用户管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  if (doc) {
    var result3 = await remove(usersModel, { userid });
    res.sendResult(result3, 200, `删除了用户:${userid}`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//添加视频标签
module.exports.addVideoLabel = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  let label = req.body.label;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  let needRole = '视频管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  if (doc) {
    var findLabel = await find(videolabelModel, { label });
    if (findLabel.length === 0) {
      var result3 = await createOne(videolabelModel, { label });
      res.sendResult(result3, 200, `已经创建了标签`);
    } else {
      res.sendResult(null, 403, `标签已存在`);
    }
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//视频标签
module.exports.removeVideoLabel = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  let label = req.body.label;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  let needRole = '视频管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  if (doc) {
    var result3 = await remove(videolabelModel, { label });
    res.sendResult(result3, 200, `删除标签`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//用户根据性别统计
module.exports.groupByGender = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  if (doc) {
    var result3 = await groupBy(usersModel, [
      {
        $group: {
          _id: "$gender",
          count: { $sum: 1 },
        },
      },
    ]);
    res.sendResult(result3, 200, `删除标签`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//根据用户地区进行统计
module.exports.groupbyUserLocation = async (req, res) => {
  let loginUserid = req.query.loginUserid;
console.log(loginUserid)
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  console.log(doc);
  if (doc) {
    var result3 = await groupBy(usersModel, [
      {
        $project: {
          location: { $substr: ["$location", 0, 9] },
          count: 1, //每组内有多少个成员
        },
      },
      {
        $group: {
          _id: "$location",
          count: { $sum: 1 },
        },
      },
    ]);
    res.sendResult(result3, 200, `删除标签`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//根据视频地区进行统计
module.exports.groupbyVideoLocation = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  if (doc) {
    var result3 = await groupBy(videosModel, [
      {
        $project: {
          location: { $substr: ["$position", 0, 9] },
          count: 1, //每组内有多少个成员
        },
      },
      {
        $group: {
          _id: "$location",
          count: { $sum: 1 },
        },
      },
    ]);
    res.sendResult(result3, 200, `删除标签`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//根据视频风格类型进行统计
module.exports.groupByVideoLabel = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  if (doc) {
    var result3 = await groupBy(videosModel, [
      { $unwind: "$choosenVideoLabel" },
      {
        $group: {
          _id: "$choosenVideoLabel",
          count: { $sum: 1 },
        },
      },
    ]);
    res.sendResult(result3, 200, `删除标签`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//根据视频发布时间进行统计
module.exports.groupByPublicTime = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  if (doc) {
    var result3 = await groupBy(videosModel, [
      {
        $project: {
          publictime: { $substr: ["$publictime", 0, 10] },
          count: 1, //每组内有多少个成员
        },
      },
      {
        $group: {
          _id: "$publictime",
          count: { $sum: 1 },
        },
      },
      {
        $sort: { publictime: -1 },
      },
    ]);
    res.sendResult(result3, 200, `删除标签`);
  } else {
    res.sendResult(null, 403, `您没有权限`);
  }
};

//根据用户粉丝进行排序
module.exports.rankByUserId = async (req, res) => {
  var data = {
    curPage: page,
    pageSize: 6,
  };
  var page = req.query.page || 1;
  const total = await count(usersModel, {});
  var result2 = await find(usersModel, {}, null, {
    skip: (page - 1) * data.pageSize,
    limit: data.pageSize,
    sort: { userid: 1 },
  });
  if (result2) {
    return res.sendResult(result2, 200, total);
  }
};

//根据用户关注进行排序
module.exports.rankByName = async (req, res) => {
  var data = {
    curPage: page,
    pageSize: 6,
  };
  var page = req.query.page || 1;
  const total = await count(usersModel, {});
  var result2 = await find(usersModel, {}, null, {
    skip: (page - 1) * data.pageSize,
    limit: data.pageSize,
    sort: { name: -1 },
  });
  if (result2) {
    return res.sendResult(result2, 200, total);
  }
};

//根据喜欢人数进行排序
module.exports.getVideoRankByLikeNum = async (req, res) => {
  var data = {
    curPage: page,
    pageSize: 6,
  };
  var page = req.query.page || 1;
  const total = await count(videosModel, {});
  var result2 = await find(videosModel, {}, null, {
    skip: (page - 1) * data.pageSize,
    limit: data.pageSize,
    sort: { likeNum: -1 },
  });
  if (result2) {
    return res.sendResult(result2, 200, total);
  }
};
module.exports.findVideos = async (req, res) => {
  let params = req.body.params;
  let page = req.body.page;
  const total = await count(videosModel, {
    $or: [{
      introduce: { $regex: req.body.params.introduce },
      userid: { $regex: req.body.params.userid },
      position: { $regex: req.body.params.position }
    }]
  });
  var docs = await find(videosModel, {
    $or: [{
      introduce: { $regex: req.body.params.introduce },
      userid: { $regex: req.body.params.userid },
      position: { $regex: req.body.params.position }
    }]
  }, null, {
    skip: (page.pageNumber - 1) * page.pageSize,
    limit: page.pageSize,
    sort: { [page.sortColumn.column]: page.sortColumn.order },
  });
  if (docs) {
    res.sendResult(docs, 200, total);
  } else {
    res.sendResult(docs, 200, "查询失败");
  }
};

module.exports.editVideos = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });

  let needRole = '视频管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  let params = req.body;
  var docs = await updateOne(videosModel, { _id: req.body._id }, req.body);
  if (docs) {
    res.sendResult(docs, 200, "修改成功");
  } else {
    res.sendResult(docs, 200, "修改失败");
  }
};

module.exports.findUsers = async (req, res) => {
  let params = req.body.params;
  let page = req.body.page;
  const total = await count(usersModel, {
    $or: [{
      userid: { $regex: req.body.params.userid },
      name: { $regex: req.body.params.name }
    }]
  });
  var docs = await find(usersModel, {
    $or: [{
      userid: { $regex: req.body.params.userid },
      name: { $regex: req.body.params.name }
    }]
  }, null, {
    skip: (page.pageNumber - 1) * page.pageSize,
    limit: page.pageSize,
    sort: { [page.sortColumn.column]: page.sortColumn.order },
  });
  if (docs) {
    res.sendResult(docs, 200, total);
  } else {
    res.sendResult(docs, 200, "查询失败");
  }
};

module.exports.editUsers = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });

  let needRole = '用户管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  let params = req.body;
  var docs = await updateOne(usersModel, { userid: req.body.userid }, req.body);
  if (docs) {
    res.sendResult(docs, 200, "修改成功");
  } else {
    res.sendResult(docs, 200, "修改失败");
  }
};

module.exports.findAdminUsers = async (req, res) => {
  let params = req.body.params;
  let page = req.body.page;
  const total = await count(administratorsModel, {
    $or: [{
      userid: { $regex: req.body.params.userid },
      permission: { $regex: req.body.params.permission }
    }]
  });
  var docs = await find(administratorsModel, {
    $or: [{
      userid: { $regex: req.body.params.userid },
      permission: { $regex: req.body.params.permission }
    }]
  }, null, {
    skip: (page.pageNumber - 1) * page.pageSize,
    limit: page.pageSize,
    sort: { [page.sortColumn.column]: page.sortColumn.order },
  });
  if (docs) {
    res.sendResult(docs, 200, total);
  } else {
    res.sendResult(docs, 200, "查询失败");
  }
};

module.exports.editAdminUsers = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });

  let needRole = '超级管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  var docs = await updateOne(administratorsModel, 
    { userid: req.body.userid },
    req.body);
  if (docs) {
    res.sendResult(docs, 200, "修改成功");
  } else {
    res.sendResult(docs, 200, "修改失败");
  }
};

module.exports.deleteAdminUsers = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });
  let needRole = '超级管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  let params = req.body;
  var docs = await remove(administratorsModel, { userid: req.body.userid });
  if (docs) {
    res.sendResult(docs, 200, "修改成功");
  } else {
    res.sendResult(docs, 200, "修改失败");
  }
};

